package com.iweipan.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iweipan.R;
import com.iweipan.activity.GetMoneyActivity;
import com.iweipan.activity.MoneyActivity;
import com.iweipan.activity.MyQuanActivity;
import com.iweipan.activity.WPHomeActivity;
import com.iweipan.activity.WPMessageActivity;
import com.iweipan.activity.WPUserInfoActivity;
import com.iweipan.base.WPBaseFragment;
import com.iweipan.utils.sputils.SPUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Random;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

import static com.iweipan.base.WPUrlBase.WP_USER_BALANCES;
import static com.iweipan.base.WPUrlBase.WP_USER_COUNTS;
import static com.iweipan.base.WPUrlBase.WP_USER_CUSTOMER;

/**
 * Created by Administrator on 2016/11/17.
 */

public class FourFragment extends WPBaseFragment implements View.OnClickListener {


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.circleImageView)
    CircleImageView circleImageView;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.clear)
    Button clear;
    @BindView(R.id.telPhone)
    TextView telPhone;
    @BindView(R.id.call_tel)
    TextView callTel;
    @BindView(R.id.message)
    ImageView message;

    @BindView(R.id.lay_out)
    RelativeLayout layOut;

    private String[] texts = {"充值", "提现", "余额", "体验券"};
    private int[] icons = {R.mipmap.chongzhi_icon, R.mipmap.tixian_icon, R.mipmap.yue_icon, R.mipmap.tiyanjuan_icon};
    private int[] ids = {R.id.pay, R.id.get, R.id.my_money, R.id.quan};
    private static final String MY_MONEY = "MY_MONEY";
    private static final String MY_QUAN = "MY_QUAN";
    private String token;
    private int addNum;
    private String myMoney = "0";
    private String my_quan_string = null;
    private String userName;


    public static FourFragment newInstance() {

        Bundle args = new Bundle();

        FourFragment fragment = new FourFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void initData() {
        clear.setOnClickListener(this);
        message.setOnClickListener(this);
        layOut.setOnClickListener(this);
        callTel.setOnClickListener(this);
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                Intent intent = new Intent(mActivity, WPHomeActivity.class);
                getActivity().startActivity(intent);
                getActivity().finish();

                return false;
            }
        });
    }

    public void reFresh() {
        initViewNow();
    }

    @Override
    public void initDestrory() {

    }

    @Override
    public void initView() {

    }

    @Override
    public void onResume() {
        super.onResume();
        initViewNow();
    }

    class RandomHan {
        private Random ran = new Random();
        private final static int delta = 0x9fa5 - 0x4e00 + 1;

        public char getRandomHan() {
            return (char) (0x4e00 + ran.nextInt(delta));
        }
    }

    private void initViewNow() {
        boolean isLogin = (boolean) SPUtils.get(mActivity, "isLogin", false);
        String user_icon = (String) SPUtils.get(mActivity, "user_icon", "");
        String user_name = (String) SPUtils.get(mActivity, "user_name", "");
        if (isLogin) {
            clear.setVisibility(View.VISIBLE);
            if (!user_icon.equals("")) {
                OkHttpUtils.get()
                        .url(user_icon)
                        .build()
                        .execute(new BitmapCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                e.printStackTrace();
                            }

                            @Override
                            public void onResponse(Bitmap response, int id) {
                                circleImageView.setImageBitmap(response);
                            }
                        });
            }
            if (!user_name.equals("")) {
                name.setText(user_name);
            }



        } else {
            clear.setVisibility(View.GONE);
        }
        token = (String) SPUtils.get(mActivity, "wp_token", "空");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("token", token);
            OkHttpUtils.get()
                    .url(WP_USER_CUSTOMER)
                    .addParams("p", jsonObject.toString())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
//                            Log.e("FourFragment", response);
                            try {
                                JSONObject requre = new JSONObject(response);
                                String code = requre.getString("code");
                                if (code.equals("200")) {
                                    JSONObject result = requre.getJSONObject("result");
                                    String mobile = result.getString("mobile");
                                    telPhone.setText(mobile);
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < texts.length; i++) {
            RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(ids[i]);
            ImageView icon = (ImageView) relativeLayout.findViewById(R.id.icon);
            icon.setImageResource(icons[i]);
            TextView textView = (TextView) relativeLayout.findViewById(R.id.one_text);
            textView.setText(texts[i]);
            TextView num_text = (TextView) relativeLayout.findViewById(R.id.num_text);
            if (i == 2) {
                initOkHttp(num_text, 0);
            } else if (i == 3) {
                initOkHttp(num_text, 1);
            }
            relativeLayout.setOnClickListener(this);
        }
    }

    private void initOkHttp(TextView num_text, int type) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("token", token);
            String[] strings = {MY_MONEY, MY_QUAN};
            String[] urls = {WP_USER_BALANCES, WP_USER_COUNTS};
            OkHttpUtils.get()
                    .url(urls[type])
                    .addParams("p", jsonObject.toString())
                    .build()
                    .execute(new MyStringCallBack(strings[type], num_text));
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private class MyStringCallBack extends StringCallback {
        private String type;
        private TextView textView;

        public MyStringCallBack(String type, TextView textView) {
            this.type = type;
            this.textView = textView;
        }

        @Override
        public void onError(Call call, Exception e, int id) {

        }

        @Override
        public void onResponse(String response, int id) {
//            Log.e("MyStringCallBack", response);
            try {
                JSONObject requry = new JSONObject(response);
                String code = requry.getString("code");
                if (code.equals("200")) {
                    if (type == MY_QUAN) {
                        my_quan_string = response;
                        JSONArray result = requry.getJSONArray("result");
                        addNum = 0;
                        if (result != null && result.length() > 0) {
                            for (int i = 0; i < result.length(); i++) {
                                JSONObject NUM = result.getJSONObject(i);
                                int num = NUM.getInt("NUM");
                                addNum += num;
                            }
                        }
                        textView.setText(addNum + "张");
                    } else if (type == MY_MONEY) {
                        myMoney = requry.getString("result");
                        textView.setText(myMoney + "元");

                    }
                } else if (code.equals("1078")) {

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public View inflaterView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_four, null);
    }

    private Handler handler;


    @Override
    public void onClick(View v) {
        boolean isLogin = (boolean) SPUtils.get(mActivity, "isLogin", false);
        switch (v.getId()) {
            case R.id.pay:
                if (isLogin) {
                    Intent intent = new Intent(getContext(), MoneyActivity.class);
                    intent.putExtra("token", token);
                    intent.putExtra("myMoney", myMoney);
                    startActivity(intent);
                }

                Log.d("FourFragment", "0");
                break;
            case R.id.get:
                Log.d("FourFragment", "1");
                if (isLogin) {
                    Intent getMoneyActivity = new Intent(mActivity, GetMoneyActivity.class);
                    getMoneyActivity.putExtra("token", token);
                    getMoneyActivity.putExtra("mobile", telPhone.getText().toString());
                    getMoneyActivity.putExtra("myMoney", myMoney);
                    startActivity(getMoneyActivity);
                }
                break;
            case R.id.my_money:
                Log.d("FourFragment", "2");

                break;
            case R.id.quan:
                Log.d("FourFragment", "3");
                if (my_quan_string != null) {
                    Intent intent = new Intent(mActivity, MyQuanActivity.class);
                    intent.putExtra("my_quan_string", my_quan_string);
                    intent.putExtra("token", token);
                    startActivity(intent);
                }

                break;
            case R.id.call_tel:
                Log.d("FourFragment", "4");
                Intent call = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + callTel.getText().toString().substring(5));
                call.setData(data);
                startActivity(call);
                break;
            case R.id.clear:
                if (isLogin) {
                    SPUtils.clear(mActivity);
                    handler.sendEmptyMessageDelayed(0, 1000);
                }
                break;
            case R.id.message:
                if (isLogin) {
                    Intent intent = new Intent(mActivity, WPMessageActivity.class);
                    startActivity(intent);
                }
                break;

            case R.id.lay_out:
                if (isLogin) {
                    Intent userInfo = new Intent(mActivity, WPUserInfoActivity.class);
                    userInfo.putExtra("user_name",name.getText().toString());
                    startActivity(userInfo);
                }
                break;
        }

    }
}
